<template>
  <a-modal
    title="新增報價單"
    :width="760"
    :visible="visible"
    :confirmLoading="loading"
    @ok="handleSubmit"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading" style="padding:15px 25px;">
      <a-form :form="form" v-bind="formLayout">
        <a-row class="form-row" :gutter="48">
          <div v-for="(v, k) in fields" :key="k">
            <a-col :lg="12" :md="12" :sm="24">
              <a-form-item :label="v.label">
                <template v-if="v.type == 'select'">
                  <a-select
                    v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required,message: v.message}]}]"
                    @change="v.onChange">
                    <a-select-option :key="sk" v-for="(item,sk) in selectList[v.listName]" :value="v.listValue?item[v.listValue]:item">{{
                      item[v.listLabel] }}
                    </a-select-option>
                  </a-select>
                </template>
                <template v-else-if="v.type == 'textarea'">
                  <a-textarea :auto-size="{ minRows: 5, maxRows: 10 }" v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required,message: v.message}]}]"/>
                </template>
                <template v-else-if="v.type == 'password'">
                  <a-input-password v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required,message: v.message}]}]" placeholder="請輸入密碼"/>
                </template>
                <template v-else-if="v.type == 'upload'">
                  <a-upload
                    name="file"
                    :showUploadList="false"
                    :customRequest="upload"
                  >
                    <a-button> <a-icon type="upload" /> Click to Upload </a-button>
                  </a-upload>
                  <span v-if="model!==null">{{ model[v.key] }}</span>
                </template>
                <template v-else-if="v.type == 'date'">
                  <a-date-picker valueFormat="yyyy-MM-DD" v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required,message: v.message}]}]" />
                </template>
                <template v-else-if="v.type == 'number'">
                  <a-input v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required, min: 0, message: v.message, type: 'number',transform(value){return Number(value)}}]}]"/>
                </template>
                <template v-else>
                  <a-input v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required, min: 0, message: v.message}]}]"/>
                </template>
              </a-form-item>
            </a-col>
          </div>
        </a-row>
      </a-form>
      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd">添加貨品</a-button>
      </div>
      <a-table :columns="columns" :data-source="data" :pagination="false">
        <a slot="name" slot-scope="text">{{ text }}</a>
        <span slot="customTitle"><a-icon type="smile-o" /> Name</span>
        <span slot="tags" slot-scope="tags">
          <a-tag
            v-for="tag in tags"
            :key="tag"
            :color="tag === 'loser' ? 'volcano' : tag.length > 5 ? 'geekblue' : 'green'"
          >
            {{ tag.toUpperCase() }}
          </a-tag>
        </span>
        <span slot="type" slot-scope="type">
          {{ type | typeFilter }}
        </span>
        <span slot="action" slot-scope="text, record ,index">
          <a @click="handleDelete(index)">删除</a>
        </span>
      </a-table>
    </a-spin>
    <create-form-goods
      ref="createModal"
      :visible="visibleGoods"
      :loading="confirmLoading"
      :model="mdlGoods"
      @cancel="handleCancel"
      @ok="handleOk"
    />
  </a-modal>
</template>

<script>
    import pick from 'lodash.pick'
    import { _post, _put } from '@/api/Quotation'
    import { _upload } from '@/api/Upload'
    import { _getAllSupplier } from '@/api/supplier'
    import CreateFormGoods from '../forms/QuotationGood'

    // 表单字段
    const fields = [
        { key: 'idSup', label: '所屬供應商', required: true, message: '', type: 'select', listName: 'supplierList', listValue: 'idSup', listLabel: 'name' },
        { key: 'no', label: '報價單編號', required: true, message: '' },
        { key: 'quotationDate', label: '報價單日期', required: true, message: '', type: 'date' },
        { key: 'quotationDueDate', label: '過期日', required: true, message: '', type: 'date' },
        { key: 'remark', label: '備註', required: true, message: '', type: 'textarea' },
        { key: 'pictureUrl', label: '報價單文件  ', required: true, message: '', type: 'upload' }
    ]

    const columns = [
      {
        title: '貨品名稱',
        dataIndex: 'nameHk'
      },
      {
        title: '貨品編號',
        dataIndex: 'no'
      },
      {
        title: '批次號',
        dataIndex: 'batchNo'
      },
      {
        title: '貨品類別',
        dataIndex: 'category'
      },
      {
        title: '類型',
        dataIndex: 'type',
        scopedSlots: { customRender: 'type' }
      },
      {
        title: '每單位貨品數量',
        dataIndex: 'piecesPerUnit'
      },
      {
        title: '貨品單位',
        dataIndex: 'unit'
      },
      {
        title: '貨品價格',
        dataIndex: 'pricePerUnit'
      },
      {
        title: '折扣',
        dataIndex: 'discount'
      },
      {
        title: '操作',
        key: 'action',
        scopedSlots: { customRender: 'action' }
      }
    ]

    export default {
        props: {
            visible: {
                type: Boolean,
                required: true
            },
            model: {
                type: Object,
                default: () => null
            }
        },
      components: {
        CreateFormGoods
      },
        data () {
            this.formLayout = {
            }
            return {
                form: this.$form.createForm(this),
                fields: fields,
                loading: false,
                selectList: {
                  supplierList: []
                },
                headers: {
                  authorization: 'authorization-text'
                },
              data: [],
              columns,
              visibleGoods: false,
              mdlGoods: null
            }
        },
        created () {
            // 防止表单未注册
            fields.forEach((v, i) => this.form.getFieldDecorator(v.key))
            // 当 model 发生改变时，为表单设置值
            this.$watch('model', () => {
                this.model && this.form.setFieldsValue(pick(this.model, fields))
            })
        },
        mounted () {
          _getAllSupplier().then((ret) => {
            this.selectList.supplierList = ret.data
          })
        },
        filters: {
          typeFilter (type) {
            if (type === 0) {
              return '乾貨'
            } else {
              return '蔬菜'
            }
          }
        },
        methods: {
            // handler
            handleSubmit (e) {
                e.preventDefault()
                this.$emit('handleRefresh')
                this.form.validateFields((err, values) => {
                    if (!err) {
                        // 新增
                        this.loading = true
                        if (values.idQuo != null) {
                            _put(values).then((res) => this.handleSuccess(res))
                        } else {
                          values['pictureUrl'] = this.model.pictureUrl
                          values['quotationGoodListStr'] = JSON.stringify(this.data)
                            _post(values).then((res) => this.handleSuccess(res))
                        }
                    }
                })
            },
            handleSuccess (ret) {
                this.loading = false
                if (ret.code === 0) {
                    this.form.resetFields()
                  this.data = []
                    this.$emit('cancel')
                    this.$message.info(ret.msg)
                } else {
                    this.$message.error('res.msg')
                }
            },
            upload (info) {
              const that = this
              var data = new FormData()
              // 创建一个表单数据
              data.append('file', info.file)
              _upload(data).then((ret) => {
                if (that.model) {
                  that.model.pictureUrl = ret.data.data
                } else {
                  that.model = {
                    pictureUrl: ret.data.data
                  }
                }
              })
            },
          handleAdd () {
            this.mdlGoods = null
            this.visibleGoods = true
          },
          handleDelete (index) {
            this.visibleGoods = false
            this.data.splice(index, 1)
          },
          handleCancel () {
            this.visibleGoods = false
            this.$refs.table.refresh() // 刷新表格
            const form = this.$refs.createModal.form
            form.resetFields() // 清理表单数据（可不做）
            this.data = []
          },
          handleOk (data) {
            // 解釋Goods對象並平鋪

            this.data.push(data)
            this.visibleGoods = false
            const form = this.$refs.createModal.form
            form.resetFields() // 清理表单数据（可不做）
          }
        }
    }
</script>
